//
//  HJTools.m
//  KaiChat
//
//  Created by lx on 2023/10/17.
//

#import "HJTools.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

static  HJTools *instance = nil;



@implementation HJTools

+ (HJTools *)tool {
    return [[HJTools alloc] init];
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (instance == nil) {
            instance = [super allocWithZone:zone];
        }
    });
    return instance;
}

- (id)copyWithZone:(NSZone *)zone {
    return instance;
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    return instance;
}


+ (BOOL)verifyPassword:(NSString *)password {
    NSString *passwordRegex = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[,.!~@#$%^&*()\\-=?<>]).{8,15}$";
    NSPredicate *passwordTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", passwordRegex];
    return [passwordTest evaluateWithObject:password];
}

+ (UINavigationController *)currentNavController {
    return [self currentViewController].navigationController;
}

+ (UINavigationController *)currentNav {
    UITabBarController *tabBarController = (UITabBarController *)[self rootViewController];
    return tabBarController.selectedViewController;
}

+ (UIViewController *)currentViewController {
    return [self getCurrentViewControllerFrom:getMainWindow().rootViewController];
}

+ (UIViewController *)getCurrentViewControllerFrom:(UIViewController *)rootVC {
    UIViewController *currentVC;
    if ([rootVC presentedViewController]) {
        rootVC = [rootVC presentedViewController];
    }
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        currentVC = [self getCurrentViewControllerFrom:[(UITabBarController *)rootVC selectedViewController]];
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        currentVC = [self getCurrentViewControllerFrom:[(UINavigationController *)rootVC topViewController]];
    } else {
        currentVC = rootVC;
    }
    return currentVC;
}

+ (NSString *)convertFileSize:(long long)size {
    
    long kb = 1024;
    long mb = kb * 1024;
    long gb = mb * 1024;
    
    if (size >= gb) {
        return [NSString stringWithFormat:@"%.1fGB", (float) size / gb];
    } else if (size >= mb) {
        float f = (float) size / mb;
        if (f > 100) {
            return [NSString stringWithFormat:@"%.0fMB", f];
        }else{
            return [NSString stringWithFormat:@"%.1fMB", f];
        }
    } else if (size >= kb) {
        float f = (float) size / kb;
        if (f > 100) {
            return [NSString stringWithFormat:@"%.0fKB", f];
        }else{
            return [NSString stringWithFormat:@"%.1fKB", f];
        }
    } else {
        return [NSString stringWithFormat:@"%lldB", size];
    }
}

+ (UIViewController *)rootViewController {
    return getMainWindow().rootViewController;
}
 

// 获取视频第一帧
+ (UIImage *)getVideoFirstViewImageWithURL:(NSURL *)path options:(NSDictionary *)options {
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:path options:options];
    AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetGen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.1, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return videoImage;
}

+ (UIImage *)getVideoFirstViewImageWithURL:(NSURL *)URL {
    return [self getVideoFirstViewImageWithURL:URL options:nil];
}

+ (UIImage *)getIMVideoFirstViewImageWithURL:(NSURL *)URL {
    return [self getVideoFirstViewImageWithURL:URL options:nil];
}

+ (UIImage *)getVideoFirstViewImageWithURL:(NSURL *)URL header:(NSDictionary *)header {
    return [self getVideoFirstViewImageWithURL:URL options:nil];

//    return [self getVideoFirstViewImageWithURL:URL options:@{@"AVURLAssetHTTPHeaderFieldsKey": header}];
}



+ (BOOL)writeOriginalImage:(UIImage *)image toLocalPath:(NSString *)localPath {
    return [UIImageJPEGRepresentation(image, 1) writeToURL:[NSURL fileURLWithPath:localPath] atomically:NO];
}

+ (BOOL)writeImageData:(NSData *)imageData toLocalPath:(NSString *)localPath {
    return [imageData writeToURL:[NSURL fileURLWithPath:localPath] atomically:NO];
}

+ (BOOL)writeOriginalImageData:(NSData *)imageData toLocalPath:(NSString *)localPath {
    return [imageData writeToURL:[NSURL fileURLWithPath:localPath] atomically:NO];
}

+ (BOOL)writeIMImage:(UIImage *)image toLocalPath:(NSString *)localPath {
    return [UIImageJPEGRepresentation(image, 0.6) writeToURL:[NSURL fileURLWithPath:localPath] atomically:NO];
}

+ (BOOL)writeImage:(UIImage *)image toLocalPath:(NSString *)localPath {
    return [UIImageJPEGRepresentation(image, 0.75) writeToURL:[NSURL fileURLWithPath:localPath] atomically:NO];
}

+ (BOOL)writeImage:(UIImage *)image toLocalPath:(NSString *)localPath error:(NSError **)error {
    return [UIImageJPEGRepresentation(image, 0.75) writeToFile:localPath options:NSDataWritingFileProtectionCompleteUnlessOpen error:error];
}

+ (NSString *)convertDateChatCellToString:(NSDate *)date {
    if (!date) {
        return nil;
    }
    
    if ([date isEqualToDate:[NSDate distantPast]]) {
        return @"";
    }
    
    NSDateFormatter *dateFmt = [[NSDateFormatter alloc] init];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    calendar.firstWeekday = 7;
    NSDateComponents *nowComponent = [calendar components:NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear|NSCalendarUnitWeekOfMonth fromDate:NSDate.new];
    NSDateComponents *dateCompoent = [calendar components:NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear|NSCalendarUnitWeekOfMonth fromDate:date];
    
    NSString *str = nil;
    if (nowComponent.year == dateCompoent.year) {
        // Same year
        if (nowComponent.month == dateCompoent.month) {
            //大于一个星期, 小于一个星期
            if (nowComponent.day - dateCompoent.day < 7) {//显示星期
                
                if (nowComponent.day == dateCompoent.day) {
                    dateFmt.dateFormat = @"HH:mm";
                    str = [dateFmt stringFromDate:date];
                } else {
                    if (nowComponent.day - dateCompoent.day == 1) {
                        dateFmt.dateFormat = @"HH:mm";
                        str = [NSString stringWithFormat:@"昨天 %@", [dateFmt stringFromDate:date]];
                    } else {
                        dateFmt.dateFormat = @"EEEE";
                        NSString *weekString = [dateFmt stringFromDate:date];
                        dateFmt.dateFormat = @"HH:mm";
                        str = [NSString stringWithFormat:@"%@ %@", weekString, [dateFmt stringFromDate:date]];
                    }
                }
            } else {//显示日和月
                dateFmt.dateFormat = @"MM月dd日";
                NSString *month = [dateFmt stringFromDate:date];
                dateFmt.dateFormat = @"HH:mm";
                str = [NSString stringWithFormat:@"%@ %@", month, [dateFmt stringFromDate:date]];
            }
        } else {
            // Not same month
            dateFmt.dateFormat = @"MM月dd日";
            str = [dateFmt stringFromDate:date];
        }
    } else {
        // Not same year
        dateFmt.dateFormat = @"yyyy年MM月dd日";
        str = [dateFmt stringFromDate:date];
    }
    
    return str;
}

+ (NSString *)convertDateChatSessionListToString:(NSDate *)date {
    if (!date) {
        return nil;
    }
    
    if ([date isEqualToDate:[NSDate distantPast]]) {
        return @"";
    }
    
    NSDateFormatter *dateFmt = [[NSDateFormatter alloc] init];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    calendar.firstWeekday = 7;
    NSDateComponents *nowComponent = [calendar components:NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear|NSCalendarUnitWeekOfMonth fromDate:NSDate.new];
    NSDateComponents *dateCompoent = [calendar components:NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear|NSCalendarUnitWeekOfMonth fromDate:date];
    
    NSString *str = nil;
    if (nowComponent.year == dateCompoent.year) {
        // Same year
        if (nowComponent.month == dateCompoent.month) {
            // Same month
            
            //大于一个星期, 小于一个星期
            if (nowComponent.day - dateCompoent.day < 7) {//显示星期
                
                if (nowComponent.day == dateCompoent.day) {
                    dateFmt.dateFormat = @"HH:mm";
                    str = [dateFmt stringFromDate:date];
                } else {
                    if (nowComponent.day - dateCompoent.day == 1) {
                        dateFmt.dateFormat = @"HH:mm";
                        str = [NSString stringWithFormat:@"昨天 %@", [dateFmt stringFromDate:date]];
                    } else {
                        dateFmt.dateFormat = @"EEEE";
                        str = [dateFmt stringFromDate:date];
                    }
                }
            } else {//显示日和月
                dateFmt.dateFormat = @"MM月dd日";
                str = [dateFmt stringFromDate:date];
            }
        } else {
            // Not same month
            dateFmt.dateFormat = @"MM月dd日";
            str = [dateFmt stringFromDate:date];
        }
    } else {
        // Not same year
        dateFmt.dateFormat = @"yyyy年MM月dd日";
        str = [dateFmt stringFromDate:date];
    }
    
    return str;
}


+ (NSString *)convertDateToString:(NSDate *)date {
    if (!date) {
        return nil;
    }
    
    if ([date isEqualToDate:[NSDate distantPast]]) {
        return @"";
    }
    
    NSDateFormatter *dateFmt = [[NSDateFormatter alloc] init];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    calendar.firstWeekday = 7;
    NSDateComponents *nowComponent = [calendar components:NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear|NSCalendarUnitWeekOfMonth fromDate:NSDate.new];
    NSDateComponents *dateCompoent = [calendar components:NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear|NSCalendarUnitWeekOfMonth fromDate:date];
    
    NSString *str = nil;
    if (nowComponent.year == dateCompoent.year) {
        // Same year
        if (nowComponent.month == dateCompoent.month) {
            // Same month
            
            //大于一个星期, 小于一个星期
            if (nowComponent.day - dateCompoent.day < 7) {//显示星期
                
                if (nowComponent.day == dateCompoent.day) {
                    dateFmt.dateFormat = @"HH:mm";
                    str = [dateFmt stringFromDate:date];
                } else {
                    if (nowComponent.day - dateCompoent.day == 1) {
                        dateFmt.dateFormat = @"HH:mm";
                        str = [NSString stringWithFormat:@"昨天 %@", [dateFmt stringFromDate:date]];
                    } else {
                        dateFmt.dateFormat = @"EEEE";
                        NSString *weekString = [dateFmt stringFromDate:date];
                        dateFmt.dateFormat = @"HH:mm";
                        str = [NSString stringWithFormat:@"%@ %@", weekString, [dateFmt stringFromDate:date]];
                    }
                }
            } else {//显示日和月
                dateFmt.dateFormat = @"MM月dd日";
                NSString *month = [dateFmt stringFromDate:date];
                dateFmt.dateFormat = @"HH:mm";
                str = [NSString stringWithFormat:@"%@ %@", month, [dateFmt stringFromDate:date]];
            }
        } else {
            // Not same month
            dateFmt.dateFormat = @"MM月dd日";
            str = [dateFmt stringFromDate:date];
        }
    } else {
        // Not same year
        dateFmt.dateFormat = @"yyyy年MM月dd日";
        str = [dateFmt stringFromDate:date];
    }
    
    return str;
}


+ (void)copyStringToPasteboard:(NSString *)string {
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = string ?: @"";
}


+ (UIImage *)convertViewToImage:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@end
